
#include <iostream>

#include "webrtc/base/scoped_ptr.h"
#include "webrtc/modules/audio_processing/beamformer/beamformer.h"
#include "webrtc/modules/audio_processing/beamformer/nonlinear_beamformer.h"
#include "webrtc/modules/audio_processing/include/audio_processing.h"
#include "webrtc/common_audio/wav_file.h"

using namespace webrtc;

int main(int argc, char *argv[])
{    
    // rtc::scoped_ptr<Beamformer<float>> beamformer_;
    std::vector<Point> array_geometry_ = {
        Point(-0.025f, 0.0f, 0.0f), Point(0.025f, 0.0f, 0.0f)
    };
    SphericalPointf target_direction_(DegreesToRadians(90.0f), 0.0, 1.0f);

    NonlinearBeamformer bf(array_geometry_, target_direction_);

    bf.Initialize(16/*ms*/, 16000/*fs*/);

    int kChunksPerSecond = 100;

    ChannelBuffer<float> in_buf(256/*rtc::CheckedDivExact(16000, kChunksPerSecond)*/, 2); // 160samples, 2channel, band1
    
    ChannelBuffer<float> out_buf(256/*rtc::CheckedDivExact(16000, kChunksPerSecond)*/, 1);

    std::string infilename = argv[1];
    std::string outfilename = argv[2];
    WavReader in_file(infilename);
    WavWriter out_file(outfilename, in_file.sample_rate(), 1);

    std::vector<float> interleaved(in_buf.size());

    // printf("interleaved.size() = %ld \n", interleaved.size()); // 320 = 2channel 10ms数据
    int framecount = 0;

    while (in_file.ReadSamples(interleaved.size(), &interleaved[0]) == interleaved.size()) 
    {
        framecount++;
        // std::cout<<"frame = "<<framecount<<std::endl;
        FloatS16ToFloat(&interleaved[0], interleaved.size(), &interleaved[0]);
        Deinterleave(&interleaved[0], in_buf.num_frames(), in_buf.num_channels(), in_buf.channels());

        bf.ProcessChunk(in_buf, &out_buf);

        Interleave(out_buf.channels(), out_buf.num_frames(), out_buf.num_channels(), &interleaved[0]);
        FloatToFloatS16(&interleaved[0], interleaved.size(), &interleaved[0]);
        int len1 = interleaved.size();
        int len2 = in_buf.num_channels();
        out_file.WriteSamples(&interleaved[0], len1/len2);
    }

    std::cout<<"test beamforming OK"<<std::endl;
    return 0;
}